package pay

import (
	"encoding/json"
	"github.com/labstack/echo"
	"gopkg.in/mgo.v2/bson"
	"strconv"
	"oxy_server/model"
	"oxy_server/module/log"
	"oxy_server/until"
)

type OXYPayV2 struct{}

func NewOXYPayV2() *OXYPayV2 {
	Data := &OXYPayV2{}
	return Data
}

func (v2 *OXYPayV2) GetListHandler(c echo.Context) error {
	log.Info("GetListHandler")
	currentpage, err := strconv.Atoi(c.QueryParam("currentpage"))
	perpage, err := strconv.Atoi(c.QueryParam("perpage"))
	jsonquery := c.QueryParam("like")
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "pay_v3"
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	query, count, err := model.DB().QuerySort(M, currentpage, perpage, "-_id")
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []accounting{}
	query.All(&ps)
	str, err := json.Marshal(ps)
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":   "success",
		"data":  string(str),
		"count": count,
	})

	return nil
}

func (v2 *OXYPayV2) AddHandler(c echo.Context) error {
	a := &insertaccounting{}
	if err := c.Bind(a); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "pay_v3"
	err := model.DB().Insert(a)
	if err != nil {
		log.Error("插入出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}
func (v2 *OXYPayV2) UpdateHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("UpdateAccountingHandler", id)
	a := &insertaccounting{}
	if err := c.Bind(a); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "pay_v3"
	err := model.DB().Update(bson.M{"_id": bson.ObjectIdHex(id)}, a)
	if err != nil {
		log.Error("更新出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}
func (v2 *OXYPayV2) DelHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("DelAccountingHandler", id)
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "pay_v3"
	err := model.DB().Remove(bson.M{"_id": bson.ObjectIdHex(id)})
	if err != nil {
		log.Error("删除出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}
